<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryParams"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="分类名称" prop="classifyName">
        <el-input
          v-model="queryParams.classifyName"
          placeholder="请输入分类名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类类型" prop="classifyType">
        <el-select
          v-model="queryParams.classifyType"
          placeholder="请选择分类类型"
          clearable
          filterable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in serviceAreaTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类别" prop="business">
        <el-cascader
          v-model="queryParams.business"
          :options="categoryOptions"
          :show-all-levels="false"
          :props="{ value: 'id', emitPath: false }"
          filterable
          clearable
          style="width: 240px"
          placeholder="请选择业务类别"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:serviceArea:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:serviceArea:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:serviceArea:export']"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table
      stripe
      v-loading="loading"
      :data="serviceAreaList"
      @selection-change="handleSelectionChange"
      @sort-change="tableSortChange"
      :default-sort="{ prop: 'createTime', order: 'ascending' }"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="分类名称"
        align="center"
        prop="classifyName"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      />
      <el-table-column
        label="分类类型"
        align="center"
        prop="classifyType"
        :sort-orders="['ascending', 'descending']"
        sortable="custom"
      />
      <el-table-column label="分类说明" align="center" prop="classifyRemark" />
      <el-table-column label="业务类别" align="center" prop="business" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:serviceArea:edit']"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改sericeArea对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类类型" prop="classifyType">
          <el-select
            v-model="form.classifyType"
            placeholder="请选择分类类型"
            clearable
            filterable
            size="small"
            style="width: 350px"
          >
            <el-option
              v-for="dict in serviceAreaTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" prop="classifyName">
          <el-input
            v-model="form.classifyName"
            placeholder="请输入分类名称"
            style="width: 350px"
          />
        </el-form-item>
        <el-form-item label="分类说明" prop="classifyRemark">
          <el-input
            v-model="form.classifyRemark"
            type="textarea"
            placeholder="请输入内容"
            style="width: 350px"
          />
        </el-form-item>

        <el-form-item label="业务类别" prop="businessCategoryIds">
          <treeselect
            style="width: 350px"
            v-model="form.businessCategoryIds"
            :options="deptOptionsChild"
            placeholder="请选择业务类别"
            :disable-branch-nodes="true"
            :multiple="true"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listServiceArea,
  getServiceArea,
  delServiceArea,
  addServiceArea,
  updateServiceArea,
  exportServiceArea,
  checkServiceArea,
} from "@/api/system/serviceArea";
import { treeselect } from "@/api/system/business_category";
import { treeSelectList } from "@/mixins/systemMixin.js";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "ServiceArea",
  components: {
    Treeselect,
  },
  mixins: [treeSelectList],
  data() {
    return {
      oldClassifyName: undefined,
      oldClassifyType: undefined,
      // 遮罩层
      loading: true,
      //新增业务类别树选项
      deptOptionsChild: undefined,
      // 选中数组
      ids: [],
      names: [],
      categoryOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      pageTempName: "AUDIT_WORKFLOW_CONFIG",
      // sericeArea表格数据
      serviceAreaList: [],
      serviceAreaTypeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      checkState: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classifyType: undefined,
        classifyName: undefined,
        classifyRemark: undefined,
        business: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classifyType: [
          { required: true, message: "分类类型不能为空", trigger: "blur" },
        ],
        classifyName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" },
        ],
        businessCategoryIds: [
          { required: true, message: "业务类别不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getDicts("sys_service_type").then((response) => {
      this.serviceAreaTypeOptions = response.data;
      this.getList();
    });
    this.getTreeSelectChild(this.pageTempName);
    treeselect().then((res) => {
      if (res.code === 200) {
        this.categoryOptions = res.data;
      }
    });
  },
  methods: {
    /** 查询sericeArea列表 */
    getList() {
      this.loading = true;
      listServiceArea(this.queryParams).then((response) => {
        this.serviceAreaList = response.rows;
        if (this.serviceAreaList && this.serviceAreaList.length != 0) {
          this.serviceAreaList.forEach((item) => {
            var serviceAreaTypeOptions = this.serviceAreaTypeOptions;
            for (var i = 0; i < serviceAreaTypeOptions.length; i++) {
              if (serviceAreaTypeOptions[i].dictValue === item.classifyType) {
                item.classifyType = serviceAreaTypeOptions[i].dictLabel;
              }
            }
          });
        }

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        guid: undefined,
        classifyType: undefined,
        classifyName: undefined,
        classifyRemark: undefined,
        business: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryParams");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.guid);
      this.names = selection.map((item) => item.classifyName);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务范围";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.oldClassifyName = undefined;
      this.reset();
      const guid = row.guid || this.ids;
      getServiceArea(guid).then((response) => {
        this.form = response.data;
        this.oldClassifyName = response.data.classifyName;
        this.oldClassifyType = response.data.classifyType;
        this.open = true;
        this.title = "修改服务范围";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.guid != undefined) {
            if (
              this.oldClassifyName === this.form.classifyName &&
              this.oldClassifyType === this.form.classifyType
            ) {
              this.submitUpdateServiceArea();
            } else {
              var req = {
                classifyName: this.form.classifyName,
                classifyType: this.form.classifyType,
              };
              checkServiceArea(req).then((response) => {
                if (response.data === 0) {
                  this.submitUpdateServiceArea();
                } else {
                  this.msgError("该分类类型下分类名称重复！");
                }
              });
            }
          } else {
            var req = {
              classifyName: this.form.classifyName,
              classifyType: this.form.classifyType,
            };
            checkServiceArea(req).then((response) => {
              if (response.data === 0) {
                this.submitAddServiceArea();
              } else {
                this.msgError("该分类类型下分类名称重复！");
              }
            });
          }
        }
      });
    },
    submitUpdateServiceArea() {
      updateServiceArea(this.form).then((response) => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        } else {
          this.msgError(response.msg);
        }
      });
    },
    submitAddServiceArea() {
      addServiceArea(this.form).then((response) => {
        if (response.code === 200) {
          this.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        } else {
          this.msgError(response.msg);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const guids = row.guid || this.ids;
      const names = row.classifyName || this.names;
      this.$confirm(
        '是否确认删除【分类名称】为"' + names + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delServiceArea(guids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有符合条件的服务范围数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportServiceArea(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    tableSortChange(column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    },
  },
};
</script>